package com.game.util;

import java.util.Date;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

import com.game.pojo.AccessToken;

import net.sf.json.JSONObject;

public class AccessTokenUtil {
	
	//获取accessToken参数
	public static final String grant_type = "client_credential";
	public static final String appid = "wxbf6b9a6674300ab3";
	public static final String secret = "8c7a901da5bd77afe369893036548428";
	/**
	 * 构建客户端开销比较大，尽量小创建该实例
	 */
	
	/**
	 * 获取accessToken
	 * @return
	 */
	public static AccessToken getAccessToken(){
		Client client = ClientBuilder.newClient();
		String accessTokenJson = client.target("https://api.weixin.qq.com/cgi-bin/token")
				.queryParam("grant_type", grant_type)
				.queryParam("appid", appid)
				.queryParam("secret", secret)
				.request().get(String.class);
		client.close();
		AccessToken accessToken = new AccessToken();
		accessToken.setCreateTime(new Date().getTime());
		accessToken.setToken(parseJson(accessTokenJson));
		return accessToken;
	}
	
	/**
	 * 从服务器返回的json串解析出accessToken
	 * @param string
	 * @return
	 */
	public static String parseJson(String string){
		JSONObject jsonObject = JSONObject.fromObject(string);
		String accessToken = jsonObject.getString("access_token");
		return accessToken;
	}
}
